layui.use(['layer','form','upload'], function() {
    var layer = layui.layer, form = layui.form,upload = layui.upload;
    $('.sel-load').selLoad(function () {
        form.render('select');
        //生成单号
        generateDocNo();
        $('#receivingDate').val(getNowFormatTime());
        //币制填充
        autoCurrency();
        //创建一行空的明细
        createRow();
        //查询历史数据
        //autoAllModel();
        autoUnit();
    });
    $('.save-btn').click(function () {saveReceivingNote();});

    upload.render({
        elem: '#importExcel',url:rurl('wms/receivingNoteMember/importMember'),size:10240,exts:'xls|xlsx'
        ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        ,before:function (res) {
            show_loading();
        },done: function(res){
            if(isSuccessWarn(res)){
                var memberData = res.data;
                show_msg("成功解析："+memberData.length+" 条数据");
                $('input[name="model"]').each(function (i,o) {
                    var $model = $(o);if(isEmpty($model.val())){$model.parent().parent().remove();}
                });
                createRows(memberData);
                calculationAll();
            }
        },error:function (index, upload) {
            hide_loading();
        }
    });

});
function saveReceivingNote() {
    if(!checkedForm($('#inboundMainForm'))){return;}
    var receivingNote = $('#inboundMainForm').serializeJson(),members = obtainMemberJSON();
    receivingNote['memo'] = $('#memo').val();//备注
    receivingNote['docNo'] = $('#docNo').val();
    postJSON('wms/receivingNote/add',{"receivingNote":receivingNote,"members":members},function (res) {
        parent.reloadList();
        closeThisWin('保存成功');
    });
}
function generateDocNo() {
    show_loading();
    $.post(rurl('scm/serialNumber/generateDocNo'),{'type':'abroad_receiving_note'},function (res) {
        if(isSuccess(res)){
            $('#docNo').val(res.data);
        }
    });
}

function obtainMemberJSON() {
    var members = [],receivingNoteMember = $('#inboundMemberForm').serializeJson(),keys=[];
    for(var key in receivingNoteMember){keys.push(key);}
    $.each(receivingNoteMember[keys[0]] ||[],function (i,o) {
        var item = {};
        $.each(keys,function (j,k) {
            item[k] = receivingNoteMember[k][i];
        });
        members.push(item);
    });
    return members;
}

function createRow(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,cartonNo,netWeight,grossWeight,batchNo) {
    if($('.mindex').length==500){show_error('最多添加500条产品信息！');return;}
    $('#memberBody').append(createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,cartonNo,netWeight,grossWeight,batchNo));
    //查询历史数据
    //autoAllModel();
    autoUnit();
    initInput();
    createIndex();
    $('.tabBody').scrollTop(10000);
}

function createRows(members) {
    var mhtml = [],tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    $.each(members,function (i,o) {
        mhtml.push(createRowHtml(o.id,o.model,o.name,o.brand,o.unitName,o.quantity,o.unitPrice,o.totalPrice,o.cartonNum,o.cartonNo,o.netWeight,o.grossWeight,o.batchNo));
        tquantity+=o.quantity;ttotalPrice+=o.totalPrice;tcartonNum+=o.cartonNum;tnetWeight+=o.netWeight;tgrossWeight+=o.grossWeight;
    });
    $('#memberBody').append(mhtml.join(''));
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
    //查询历史数据
    //autoAllModel();
    autoUnit();
    initInput();
    createIndex();
}

function createRowHtml(mid,goodsModel,goodsName,goodsBrand,unitName,quantity,unitPrice,totalPrice,cartonNum,cartonNo,netWeight,grossWeight,batchNo) {
    return [
        '<tr><td class="t-a-c mindex"></td>',
        '<td><input type="hidden" name="id" LIST value="'+(isEmpty(mid)?'':mid)+'"/><input type="text" name="model" LIST class="layui-input required auto-customer-model" placeholder="型号" value="'+(isEmpty(goodsModel)?'':goodsModel)+'"/></td>',
        '<td><input type="text" name="name" LIST class="layui-input" value="'+(isEmpty(goodsName)?'':goodsName)+'"/></td>',
        '<td><input type="text" name="brand" LIST class="layui-input required" value="'+(isEmpty(goodsBrand)?'':goodsBrand)+'"/></td>',
        '<td><input type="text" name="unitName" LIST class="layui-input auto-unit required" value="'+(isEmpty(unitName)?'个':unitName)+'"/></td>',
        '<td><input type="text" name="quantity" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(quantity)?'':quantity)+'"/></td>',
        '<td><input type="text" name="unitPrice" LIST class="layui-input layui-disabled" readonly value="'+(isEmpty(unitPrice)?'0.0000':unitPrice)+'"/></td>',
        '<td><input type="text" name="totalPrice" LIST onblur="calculationAll(this)" NUMBER class="layui-input required" value="'+(isEmpty(totalPrice)?'':totalPrice)+'"/></td>',
        '<td><input type="text" name="cartonNum" LIST onblur="calculationAll()" INT class="layui-input required" value="'+(isEmpty(cartonNum)?'0':cartonNum)+'"/></td>',
        '<td><input type="text" name="cartonNo" LIST class="layui-input" value="'+(isEmpty(cartonNo)?'':cartonNo)+'"/></td>',
        '<td><input type="text" name="netWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(netWeight)?'0.0000':netWeight)+'"/></td>',
        '<td><input type="text" name="grossWeight" LIST NUMBER4 onblur="calculationAll()" class="layui-input required" value="'+(isEmpty(grossWeight)?'0.0000':grossWeight)+'"/></td>',
        '<td><input type="text" name="batchNo" LIST class="layui-input" value="'+(isEmpty(batchNo)?'':batchNo)+'"/></td>',
        '<td class="t-a-c"><a href="javascript:" onclick="deleteRow(this)"><i class="fa fa-trash-o"></i></a></td></tr>'
    ].join('');
}

function createIndex() {
    var mind = 1;
    $.each($('.mindex'),function (i,o) {
        $(o).html(mind++);
    });
}

var $quantityTotal=$('#quantityTotal'),$totalPriceTotal=$('#totalPrice'),$cartonTotal=$('#cartonTotal'),$netWeightTotal=$('#netWeightTotal'),$grossWeightTotal=$('#grossWeightTotal');
function calculationAll(e) {
    var tquantity = 0.0,ttotalPrice = 0.0,tcartonNum = 0,tnetWeight = 0.0,tgrossWeight = 0.0;
    if(!isEmpty(e)){
        var $that = $(e),$parent=$that.parent().parent(),$quantity=$parent.find('input[name="quantity"]'),$unitPrice=$parent.find('input[name="unitPrice"]'),$totalPrice=$parent.find('input[name="totalPrice"]');
        switch ($that.attr('name')){
            case 'quantity':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
            case 'unitPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                var unitPrice = Math.round(parseFloat($unitPrice.val() || '0.0')*10000)/10000;
                $totalPrice.val(Math.round(quantity*unitPrice*100)/100);
                break;
            case 'totalPrice':
                var quantity = Math.round(parseFloat($quantity.val() || '0.0')*100)/100;
                if(quantity==0.0){$unitPrice.val('0.0000');return;}
                var totalPrice = Math.round(parseFloat($totalPrice.val() || '0.0')*100)/100;
                $unitPrice.val(Math.round(totalPrice/quantity*10000)/10000);
                break;
        }
    }
    $.each($('#memberBody').find('tr'),function (i,o) {
        var $that = $(o);
        tquantity += Math.round(parseFloat($that.find('input[name="quantity"]').val() || '0.0')*100)/100;
        ttotalPrice += Math.round(parseFloat($that.find('input[name="totalPrice"]').val() || '0.0')*100)/100;
        tcartonNum += parseInt($that.find('input[name="cartonNum"]').val() || '0');
        tnetWeight += Math.round(parseFloat($that.find('input[name="netWeight"]').val() || '0.0')*10000)/10000;
        tgrossWeight += Math.round(parseFloat($that.find('input[name="grossWeight"]').val() || '0.0')*10000)/10000;
    });
    $quantityTotal.html(Math.round(tquantity*100)/100);
    $totalPriceTotal.html(formatCurrency(Math.round(ttotalPrice*100)/100));
    $cartonTotal.html(tcartonNum);
    $netWeightTotal.html(Math.round(tnetWeight*10000)/10000);
    $grossWeightTotal.html(Math.round(tgrossWeight*10000)/10000);
}

$('.addrow-btn').click(function () {createRow();});

function deleteRow(e) {
    var $per = $(e).parent().parent();
    $per.remove();
    createIndex();
    calculationAll();
}

function fullCustomerData(data) {
    $('#customerId').val(data.id);
}

function fullCurrencyData(data) {
    $('#currencyId').val(data.code);
}
function fullCustomerModelData(e,data) {
    var $per = $(e).parent().parent();
    $per.find('input[name="name"]').val(data.name);
    $per.find('input[name="brand"]').val(data.brand);
    $per.find('input[name="spec"]').val(data.spec);
}